package com.wiscamp.ninechapters;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * application entry
 *
 * @author yifeng
 */

@EnableCaching
@EnableScheduling
@SpringBootApplication(scanBasePackages = {"cube", "com.wiscamp.ninechapters"})
@EnableAspectJAutoProxy
@EnableTransactionManagement
@ComponentScan(basePackages = {"cube", "com.wiscamp.ninechapters", "com.wiscamp.ninechapters.panels"})
public class SpringApplication extends SpringBootServletInitializer {

    @Value("${http.port}")
    private Integer httpPort;

    private static ApplicationContext applicationContext;

    /**
     * Spring boot application entry
     *
     * @param args arguments
     */
    public static void main(String[] args) {
        try {
            applicationContext = new SpringApplication()
                    .configure(new SpringApplicationBuilder(SpringApplication.class))
                    .run(args);
            // displayAllBeans();
        } catch (Throwable e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Load tomcat server factory
     *
     * @return a tomcat factory
     */
    @Bean
    public ServletWebServerFactory servletContainer() {
        var tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }

    /**
     * Set http port
     *
     * @return a connector
     */
    private Connector createStandardConnector() {
        var connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        return connector;
    }

    /**
     * 打印所以装载的bean
     */
    public static void displayAllBeans() {
        String[] allBeanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : allBeanNames) {
            System.out.println(beanName);
        }
    }

}
